package com.societyGames.codeAlong.state.codeExercise.view
{
	import com.societyGames.flashForms.IChangeSize;
	import com.societyGames.flashForms.ScrollContainer;
	import com.societyGames.flashForms.SingleItemContainer;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;

	public class ToolTip extends SingleItemContainer
	{
		private var _desiredWidth:Number;
		private var _desiredHeight:Number;
		
		public function ToolTip()
		{	
			this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
		}
		
		public function show(parent:Sprite, x:Number, y:Number):void
		{
			parent.addChild(this);
			var bounds:Rectangle = this.getBounds(parent);
			var parentBounds:Rectangle = parent.getBounds(parent);
			if (x < (parentBounds.x + (parentBounds.width / 2)))
			{
				this.x = x;
			}
			else
			{
				this.x = x - bounds.width;
			}
			if (y < (parentBounds.y + (parentBounds.height / 2)))
			{
				this.y = y;
			}
			else
			{
				this.y = y - bounds.height;
			}
		}
		
		public override function set height(value:Number):void
		{
			this._desiredHeight = value;
			synchronizeHeight();
		}
		
		public override function set width(value:Number):void
		{
			this._desiredWidth = value;
			synchronizeWidth();
		}
		
		public function hide():void
		{
			if (this.parent != null)
			{
				this.parent.removeChild(this);
			}
		}
		
		private function addedToStageHandler(event:Event):void
		{
			this.removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
			this.addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
			this.stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler, false);
		}
		
		private function removedFromStageHandler(event:Event):void
		{
			this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
			this.removeEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
			this.stage.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler, false);
		}
		
		private function mouseDownHandler(event:MouseEvent):void
		{
			if (!this.hitTestPoint(event.stageX, event.stageY, true))
			{
				hide();
			}
		}
		
		private function synchronizeWidth():void
		{
			if (this._item != null)
			{
				this._item.width = this._desiredWidth;	
			}	
		}
		
		private function synchronizeHeight():void
		{
			if (this._item != null)
			{
				this._item.height = this._desiredHeight;
			}
		}
		
		protected override function childSizeChangedHandler(event:Event):void
		{
			synchronizeWidth();	
			synchronizeHeight();			
		}
	}
}